#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "ota_handler.h"

#define BUFFER_SIZE 1024
#define OTA_FILE_PATH "./uploads/ota.bin"

void handle_ota_request(int client_socket, const char *target_ip) {
    (void)target_ip; // 标记参数为有意未使用
    char buffer[BUFFER_SIZE];
    int bytes_received = recv(client_socket, buffer, sizeof(buffer) - 1, 0);
    if (bytes_received < 0) {
        perror("Failed to receive data");
        close(client_socket);
        return;
    }

    buffer[bytes_received] = '\0';
    if (strcmp(buffer, "start_ota") == 0) {
        FILE *ota_file = fopen(OTA_FILE_PATH, "rb");
        if (!ota_file) {
            const char *error_message = "File not found\n";
            send(client_socket, error_message, strlen(error_message), 0);
            close(client_socket);
            return;
        }

        fseek(ota_file, 0, SEEK_END);
        long file_size = ftell(ota_file);
        fseek(ota_file, 0, SEEK_SET);

        char response_header[BUFFER_SIZE];
        snprintf(response_header, sizeof(response_header), "HTTP/1.1 200 OK\r\nContent-Length: %ld\r\nContent-Type: application/octet-stream\r\nContent-Disposition: attachment; filename=\"ota.bin\"\r\n\r\n", file_size);
        send(client_socket, response_header, strlen(response_header), 0);

        size_t bytes_sent = 0;
        while ((bytes_received = fread(buffer, 1, sizeof(buffer), ota_file)) > 0) {
            send(client_socket, buffer, bytes_received, 0);
            bytes_sent += bytes_received;
            printf("Sent %zu bytes... (%.2f%%)\n", bytes_sent, (bytes_sent / (float)file_size) * 100);
        }

        fclose(ota_file);
        printf("File download complete\n");
    } else {
        const char *error_message = "Invalid request\n";
        send(client_socket, error_message, strlen(error_message), 0);
    }

    close(client_socket);
}